package cn.xuchunh.campusbbs.ui.activities;

import android.Manifest;
import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckedTextView;
import android.widget.EditText;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.facebook.drawee.view.SimpleDraweeView;

import org.json.JSONObject;

import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.R;
import cn.xuchunh.campusbbs.base.BaseActivity;
import cn.xuchunh.campusbbs.bean.Member;
import cn.xuchunh.campusbbs.bean.User;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.net.SimpleXJsonListener;
import cn.xuchunh.campusbbs.storage.sp.SharedPreferenceManager;
import cn.xuchunh.campusbbs.storage.sqlite.DBManager;
import cn.xuchunh.campusbbs.utils.Constants;
import cn.xuchunh.campusbbs.utils.JsonKey;
import cn.xuchunh.campusbbs.widget.ProgressBarCircularIndeterminate;
import cn.xuchunh.campusbbs.widget.reveal.CircularRevealView;

public class LoginActivity extends BaseActivity {

    private AutoCompleteTextView etUserName;
    private EditText etPassword;
    private SimpleDraweeView avatar;
    private CheckedTextView textView;
    private CircularRevealView revealView;
    private ProgressBarCircularIndeterminate progressBar;

    public static final int REQUEST_READ_PHONE_STATE = 1;

    public static void launch(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void beforeInitView() {
        super.beforeInitView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected int createContentRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView(View view) {
        avatar = (SimpleDraweeView) findViewById(R.id.avatar);
        etUserName = ((AutoCompleteTextView) ((TextInputLayout) findViewById(R.id.username)).getEditText());
        etPassword = ((TextInputLayout) findViewById(R.id.password)).getEditText();

        textView = (CheckedTextView) findViewById(R.id.text);
        revealView = (CircularRevealView) findViewById(R.id.reveal_view);
        progressBar = (ProgressBarCircularIndeterminate) findViewById(R.id.progress);

        textView.setOnTouchListener(textViewTouchListener);

        etUserName.addTextChangedListener(userNameWatcher);
        etPassword.addTextChangedListener(passwordWatcher);

        etUserName.setOnKeyListener(usernameKeyListener);

        SharedPreferenceManager sharedPreferenceManager = SharedPreferenceManager.getInstance();
        if (sharedPreferenceManager.isAutoLogin()) {
            etUserName.setText(sharedPreferenceManager.getUsername());
            etPassword.setText(sharedPreferenceManager.getPassword());
            avatar.setImageURI(Uri.parse(sharedPreferenceManager.getUserAvatar()));
        }
        View editArea = findViewById(R.id.edit_area);
        ViewCompat.setElevation(editArea, getResources().getDimensionPixelSize(R.dimen.elevation));
        ViewCompat.setElevation(avatar, getResources().getDimensionPixelSize(R.dimen.elevation));

        List<Member> loginedUsers = DBManager.getInstance().loadLoginedUsers();
        ArrayAdapter<Member> adapter =
                new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, loginedUsers);
        etUserName.setAdapter(adapter);

    }

    public void login() {
        String userName = etUserName.getEditableText().toString();
        String password = etPassword.getEditableText().toString();

        HttpRequestManager.getInstance(AppContext.getInstance())
                .login(userName, password, jsonListener
                        , new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                showToast(error.getMessage());
                                int x = (int) (revealView.getX() + revealView.getWidth() / 2);
                                int y = (int) (revealView.getY() + revealView.getHeight() / 2);
                                progressBar.setVisibility(View.GONE);
                                revealView.hide(x, y, getResources().getColor(R.color.transparent), null);
                            }
                        }, "login");

    }

    private TextWatcher userNameWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            etPassword.setText("");
        }
    };

    private TextWatcher passwordWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            boolean checked = !TextUtils.isEmpty(etUserName.getEditableText().toString()) && !TextUtils.isEmpty(s.toString());
            textView.setChecked(checked);
        }
    };

    private View.OnTouchListener textViewTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getActionMasked() == MotionEvent.ACTION_DOWN && textView.isChecked()) {
                revealView.reveal((int) event.getX(), (int) event.getY(), getResources().getColor(R.color.colorAccent), revealListener);
                return true;
            }
            return false;
        }
    };

    private View.OnKeyListener usernameKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                if (TextUtils.isEmpty(etUserName.getEditableText().toString())) {
                    showToast(R.string.error_empty_username);
                } else {
                    etPassword.requestFocus();
                }

                return true;
            }
            return false;
        }
    };

    private Animator.AnimatorListener revealListener = new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {

        }

        @Override
        public void onAnimationEnd(Animator animation) {
            progressBar.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    login();
                }
            }, 500);
        }

        @Override
        public void onAnimationCancel(Animator animation) {

        }

        @Override
        public void onAnimationRepeat(Animator animation) {

        }
    };

    private SimpleXJsonListener<User> jsonListener = new SimpleXJsonListener<User>() {
        @Override
        public void onResponse(User response) {
            AppContext.getInstance().setUser(response);
            SharedPreferenceManager spManager = SharedPreferenceManager.getInstance();
            spManager.setAutologin(true);
            spManager.setUserName(response.getUserName());
            spManager.setPassword(etPassword.getEditableText().toString());
            spManager.setUserAvatar(response.getAvatar());
            DBManager.getInstance()
                    .insertLoginedUser(response.getUserName(), response.getUserId(), response.getAvatar());
            showToast(R.string.succeed_login);
            if (SharedPreferenceManager.getInstance().getUiMode() ==
                    Constants.UI_MODE_BOTTOM) {
                MainActivity.launch(LoginActivity.this);
            } else {
                DrawerMainActivity.launch(LoginActivity.this);
            }
            finish();
        }

        @Override
        public User parseData(JSONObject jsonObject) throws Exception {
            HttpRequestManager.getInstance(LoginActivity.this).
                    setToken(jsonObject.optString(JsonKey.TOKEN));
            HttpRequestManager.getInstance(LoginActivity.this).
                    setSecret(jsonObject.optString(JsonKey.SECRET));
            User user = getUser();
            user.setUserId(jsonObject.optInt(JsonKey.UID, 1));
            user.setUserName(jsonObject.optString(JsonKey.USERNAME));
            user.setAvatar(jsonObject.optString(JsonKey.AVATAR));
            user.setLogined(true);
            return user;
        }
    };

}

